#include <cmath>
#include "Sphere.h"

CSphere::~CSphere(void)
{
	delete m_Origin;
}

/*
	Method checks if ray intersects a sphere and returns way of intersection.

	Returns:
	0 - no intersection
	1 -	single point of intersection
	2 - two points of intersection
*/
int	CSphere::Intersect(CRay& _ray,  IsectData& _isecData)
{
	// Count second point on the ray (t = 1)
	// p(t) = o + td => p(1) = o + d

	CVector secondPoint = CVector((*_ray.GetOrigin()) + (*_ray.GetDirection()));
	float xA = (*_ray.GetOrigin()).GetX();
	float yA = (*_ray.GetOrigin()).GetY();
	float zA = (*_ray.GetOrigin()).GetZ();
	float xB = secondPoint.GetX();
	float yB = secondPoint.GetY();
	float zB = secondPoint.GetZ();
	float xC = (*GetOrigin()).GetX();
	float yC = (*GetOrigin()).GetY();
	float zC = (*GetOrigin()).GetZ();
	float a = powf(xB - xA, 2.0f) + powf(yB - yA, 2.0f) + powf(zB - zA, 2.0f);
	float b = 2 * ((xB - xA)*(xA - xC) + (yB - yA)*(yA - yC) + (zB - zA)*(zA - zC));
	float c = powf((xA - xC), 2.0f) + powf((yA - yC), 2.0f) + powf((zA - zC), 2.0f) - powf(m_Radius, 2.0f);
	float delta = b*b - 4*a*c;

	if (delta >= 0)
	{
		float t = 0.0f;

		if (delta == 0)
		{
			t = -b / (2.0f * a);
//			_interOneCoords = _ray.ParametricEquation(t);

			return 1;
		}

		t = (-b - sqrtf(delta))/ (2.0f * a);
//		_interOneCoords = _ray.ParametricEquation(t);
		t = (-b + sqrtf(delta))/ (2.0f * a);
//		_interTwoCoords = _ray.ParametricEquation(t);

		return 2;
	}

	return 0;
}


